package com.wujunshen.swagger;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.PathProvider;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.paths.AbstractPathProvider;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.annotation.Resource;
import java.util.ArrayList;

@Slf4j
@Configuration
@EnableSwagger2
@EnableConfigurationProperties(SwaggerProperties.class)
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class SwaggerAutoConfiguration {
    @Resource
    private SwaggerProperties swaggerProperties;

    @Bean
    public Docket apiDocket() {
        log.info("\ntitle is:{}\ndescription is:{}\nversion is:{}\n", swaggerProperties.getTitle(),
                swaggerProperties.getDescription(),
                swaggerProperties.getVersion());
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("my-api")
                .pathProvider(apiPathProvider())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .build()
                .apiInfo(new ApiInfo(
                        swaggerProperties.getTitle(),
                        swaggerProperties.getDescription(),
                        swaggerProperties.getVersion(),
                        "",
                        new Contact(swaggerProperties.getContact(), "", "frank_wjs@hotmail.com"),
                        "Apache License Version 2.0",
                        "http://www.apache.org/licenses/LICENSE-2.0.html",
                        new ArrayList<>()));
    }

    private PathProvider apiPathProvider() {
        return new AbstractPathProvider() {
            @Override
            protected String applicationPath() {
                return swaggerProperties.getContextPath();
            }

            @Override
            protected String getDocumentationPath() {
                return "";
            }
        };
    }
}